<template>
  <CommonTabbar />
  <div class="cate-page">
    <div class="cate-container">
      <div class="cates">
        <div
          v-for="(cate, index) in cates"
          :key="cate.id"
          @click="switchCateActive(index)"
          :class="[
            'cate',
            {
              active: activeIndex === index,
            },
          ]"
        >
          {{ cate.name }}
        </div>
      </div>
    </div>
    <div class="item-container">
      <div class="items">
        <van-card
          v-for="item in items"
          :key="item.id"
          :price="item.minPrice"
          :title="item.name"
          :thumb="item.pic"
          @click="clickItem(item.id)"
        >
          <template #footer>
            <van-icon
              name="gouwuchetianjia"
              color="#ff623a"
              class-prefix="icon"
              size="20"
            />
          </template>
        </van-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="CatePage">
import { ref, onMounted } from "vue";
import CommonTabbar from "@/components/CommonTabbar.vue";
import type { Cate, Item } from "@/types/homeType";
import { getCates, getItems } from "@/api/home";
import { useRouter } from "vue-router";
const router = useRouter();
const clickItem = (id: number) => {
  router.push({
    path: "/detail",
    query: {
      id,
    },
  });
};
const switchCateActive = (index: number) => {
  activeIndex.value = index;
  fetchItems();
};

// 所有分类
const cates = ref<Cate[]>([]);
// 高亮分类的商品列表
const items = ref<Item[]>([]);
// 高亮分类的下标
const activeIndex = ref(0);
// 请求所有的分类
const fetchCates = () => {
  getCates().then((res) => {
    if (res.data.code === 0) {
      cates.value = res.data.data;
      fetchItems();
    }
  });
};
// 获取高亮分类下商品
const fetchItems = () => {
  getItems({
    categoryId: cates.value[activeIndex.value].id,
  }).then((res) => {
    if (res.data.code === 0) {
      items.value = res.data.data.result;
    }
    if (res.data.code === 700) {
      items.value = [];
    }
  });
};
onMounted(() => {
  fetchCates();
});
</script>

<style scoped lang="scss">
.cate-page {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 50px;
  display: flex;
  .cate-container {
    width: 3rem;
    height: 100%;
    overflow-y: auto;
    border-right: 1px solid #ccc;
    .cate {
      line-height: 40px;
      text-align: center;
      &.active {
        color: #ff623a;
        position: relative;
        &::after {
          content: "";
          height: 40px;
          width: 2px;
          background-color: #ff623a;
          position: absolute;
          left: 0;
          top: 0;
        }
      }
    }
  }
  .item-container {
    width: 7rem;
    height: 100%;
    overflow-y: auto;
  }
}
</style>
